﻿using Soft.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Soft.Service
{
    /// <summary>
    /// 服务端方法执行器
    /// </summary>
    public sealed class ServiceRemoteMethodCallPerformer : BaseRemotingObject
    {

        public ServiceRemoteMethodCallPerformer()
        {
            Console.WriteLine($"{nameof(ServiceRemoteMethodCallPerformer)} 执行构造函数");
        }

        /// <summary>
        /// 执行invoke调用
        /// </summary>
        /// <param name="callMethodInstruction">要调用的方法</param>
        /// <returns></returns>
        public CarrierJson Invoke(CallMethodInstruction callMethodInstruction)
        {
            callMethodInstruction.ClientIPAddress = (IPAddress)CallContext.GetData("ClientIPAddress");
            CarrierJson carrierJson = new CarrierJson();
            try
            {
                carrierJson = this.ReceivedMethodCallInstruction(callMethodInstruction);
            }
            catch (Exception innerException)
            {
                InternalSystemException ex = new InternalSystemException("An error occurred in response to the remote request", this, innerException);
                JobServiceController jobService = ServiceRemoteMethodCallPerformer.JobService;
                if (jobService != null)
                {
                    jobService.OnError(new Information(ex));
                }
                carrierJson.AddError(ex, null);
            }
            return carrierJson;
        }


        /// <summary>
        /// 接收方法调用
        /// </summary>
        /// <param name="callInstruction"></param>
        /// <returns></returns>
        public CarrierJson ReceivedMethodCallInstruction(CallMethodInstruction callInstruction)
        {
            CarrierJson carrierJson = new CarrierJson();
            if (ServiceRemoteMethodCallPerformer.JobService != null)
            {
                ///JobService控制器 接收方法的调用 
                carrierJson = ServiceRemoteMethodCallPerformer.JobService.OnReceivedMethodCallInstruction(callInstruction);
            }
            else
            {
                carrierJson.AddError(new InternalSystemException("The system has stopped.", this, null), null);
            }
            return carrierJson;
        }


        /// <summary>
        /// jobService总控制器
        /// </summary>
        public static JobServiceController JobService;



    }
}
